import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount,
  userMenu
} from '@/api/user';
import { setToken, getToken, getMenuByRouter } from '@/libs/util';
import routers from '@/router/routers';
import _ from 'lodash';

// 根据路由获取的菜单
var tempList = _.cloneDeep(routers);
var newList = tempList.filter(item => {
  return !item.meta.hideInMenu;
});

newList.forEach(item => {
  if (item.children && item.children.length > 0) {
    var newChild = item.children;
    var newList1 = newChild.filter(citem => {
      return !citem.meta.hideInMenu;
    });
    item.children = newList1;
  }
});
function completePerms (respMenu) {
  console.log('通过服务器获取按钮权限');
  routers.forEach(route => {
    route.meta.perms = findPerms(route.meta.title, respMenu);
    if (route.children) {
      route.children.forEach(croute => {
        croute.meta.perms = findPerms(croute.meta.title, respMenu);
      });
    }
  });
}

function findPerms (routeMetaTitle, respMenu) {
  var perms = [];
  respMenu.forEach(menu => {
    if (routeMetaTitle) {
      if (menu.children && menu.children.length > 0) {
        // findPerms(perms, routeMetaTitle, menu.children);
        menu.children.forEach(child => {
          if (routeMetaTitle.indexOf(child.nodeName) > -1) {
            child.children.forEach(button => {
              if (button.type === 2) {
                perms.push(button.perms);
              }
            });
          }
        });
      }
    }
  });
  return perms;
}

export default {
  state: {
    username: '',
    userId: '',
    avatarImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
    waitNumber: 0, // 待办数量
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    userMenu: [] // 用户下的菜单列表
  },
  mutations: {
    getUserMenu (state, list) {
      state.userMenu = list;
    },
    setAvatar (state, avatarPath) {
      state.avatarImgPath = avatarPath;
    },
    setUserId (state, id) {
      state.userId = id;
    },
    setUserName (state, name) {
      state.username = name;
    },
    setWaitNumber (state, num) {
      state.waitNumber = num;
    },
    setAccess (state, access) {
      state.access = access;
    },
    setToken (state, token) {
      state.token = token;
      setToken(token);
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status;
    },
    setMessageCount (state, count) {
      state.unreadCount = count;
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list;
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list;
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list;
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content;
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id);
      const msgItem = state[from].splice(index, 1)[0];
      msgItem.loading = false;
      state[to].unshift(msgItem);
    }
  },
  getters: {
    menuList: (state, getters, rootState) =>
      getMenuByRouter(state.userMenu, rootState.user.access),
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { username, password }) {
      username = username.trim();
      return new Promise((resolve, reject) => {
        login({
          username,
          password
        })
          .then(res => {
            // const data = res.data;
            if (res.data.code == 200) {
              commit('setToken', 1);
              setToken(res.data.data);
              resolve();
            } else {
              reject(res);
            }
          })
          .catch(err => {
            console.log('err2', err);
            reject(err);
          });
      });
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit('setToken', '');
            commit('setAccess', []);
            commit('getUserMenu', []);
            resolve();
            setTimeout(() => {
              window.location.reload();
            }, 200);
          })
          .catch(err => {
            reject(err);
          });
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      });
    },

    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo()
            .then(res => {
              const { user, approvalCount } = res.data.data;
              const mockdata = {
                code: 200,
                msg: 'success',
                data: {
                  fullname: user.fullname
                }
              };
              const data = mockdata.data;
              // commit('setAvatar', data.avatar);
              commit('setUserName', data.fullname);
              commit('setWaitNumber', approvalCount);// 待办数量
              // commit('setUserId', data.user_id);
              commit('setAccess', ['super_admin']);
              commit('setHasGetInfo', true);
              resolve(data);
            }
            )
            .catch(err => {
              reject(err);
            });
        } catch (error) {
          reject(error);
        }
      });
    },

    getUserMenuList ({ state, commit }) {
      return new Promise((resolve, reject) => {
        userMenu()
          .then(res => {
            const result = res.data.data;
            for (var i = 0; i < newList.length; i++) {
              var itemMeta = newList[i].meta;
              itemMeta.hideInMenu = true;
              for (var j = 0; j < result.length; j++) {
                var menuItem = result[j];
                if (itemMeta.title == menuItem.nodeName) {
                  itemMeta.hideInMenu = false;
                  var routerChild = newList[i].children;
                  var menuChild = menuItem.children;
                  if (routerChild) {
                    for (var l = 0; l < routerChild.length; l++) {
                      var rMeta = routerChild[l].meta;
                      rMeta.hideInMenu = true;
                      for (var k = 0; k < menuChild.length; k++) {
                        var cItem = menuChild[k];
                        if (rMeta.title == cItem.nodeName) {
                          rMeta.hideInMenu = false;
                        }
                      }
                    }
                  }
                }
              }
            }
            // 获取按钮权限，但暂时没用
            completePerms(result);
            console.log(newList, 333333);
            commit('getUserMenu', newList);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    getUnreadMessageCount ({ state, commit }) {
      getUnreadCount().then(res => {
        const { data } = res;
        commit('setMessageCount', data.data.count);
      });
    },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList ({ state, commit }) {
      return new Promise((resolve, reject) => {
        getMessage()
          .then(res => {
            const { unread, readed, trash } = res.data;
            commit(
              'setMessageUnreadList',
              unread.sort(
                (a, b) => new Date(b.create_time) - new Date(a.create_time)
              )
            );
            commit(
              'setMessageReadedList',
              readed
                .map(_ => {
                  _.loading = false;
                  return _;
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            );
            commit(
              'setMessageTrashList',
              trash
                .map(_ => {
                  _.loading = false;
                  return _;
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            );
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 根据当前点击的消息的id获取内容
    getContentByMsgId ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id];
        if (contentItem) {
          resolve(contentItem);
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data;
            commit('updateMessageContentStore', { msg_id, content });
            resolve(content);
          });
        }
      });
    },
    // 把一个未读消息标记为已读
    hasRead ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageUnreadList',
              to: 'messageReadedList',
              msg_id
            });
            commit('setMessageCount', state.unreadCount - 1);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 删除一个已读消息到回收站
    removeReaded ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageReadedList',
              to: 'messageTrashList',
              msg_id
            });
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 还原一个已删除消息到已读消息
    restoreTrash ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageTrashList',
              to: 'messageReadedList',
              msg_id
            });
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
};
